package com.kob.backend.service.impl.user.bot;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.bot.AddService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
public class AddServiceImpl implements AddService {
    @Autowired
    private BotMapper botMapper;
    @Override
    public Map<String, String> add(Map<String, String> data) {
        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();

        User user = loginUser.getUser();

        String title = data.get("title");
        String description = data.get("description");
        String content = data.get("content");

        Map<String,String> map = new HashMap<>();

        QueryWrapper<Bot> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        if(botMapper.selectCount(queryWrapper) >= 10){
            map.put("error_message","一个用户最多同时拥有10个BOt");
            return map;
        }


        if(title == null || title.length() == 0){
            map.put("error_message","标题不能为空");
            return map;
        }

        if(title.length() > 99){
            map.put("error_message","标题长度不能大于99");
            return map;
        }
        if(description == null||description.length() == 0){
            description = "这个用户很懒，什么也没有留下(希望他明天还能记得他代码里写的啥)";
        }

        if(description.length() > 299){
            map.put("error_message","描述字数太多");
            return map;
        }
        if(content == null || content.length() == 0)
        {
            map.put("error_message","代码不能为空(你指望上天给你写代码？)");
            return map;
        }
        if(content.length()>9999){
            map.put("error_message","代码长度过长(我这整个项目代码都不一定有你长，你想上天?)");
            return map;
        }
        Date now = new Date();
        Bot bot = new Bot(null,user.getId(),title,description,content,1500,now,now);

        botMapper.insert(bot);
        map.put("error_message","success");

        return map;
    }
}
